package com.asj.house.service.impl;

import com.asj.house.entity.HouseHits;
import com.asj.house.mapper.HouseHitsMapper;
import com.asj.house.service.HouseHitsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 房屋点击量表 服务实现类
 * </p>
 *
 * @author asj
 * @since 2021-03-08
 */
@Service
public class HouseHitsServiceImpl extends ServiceImpl<HouseHitsMapper, HouseHits> implements HouseHitsService {

    @Async
    @Override
    public void houseHitsAccess(Integer roomId) {
        //判断当前房源是否存在
        HouseHits houseHits = selectHouseHits(roomId);

        if (Objects.isNull(houseHits)) {
            insertHouseHits(roomId);
        }else {
            updateHouseHits(houseHits);
        }
    }

    private void updateHouseHits(HouseHits houseHits) {
        Integer hits = houseHits.getHits();
        hits = hits + 1;
        houseHits.setHits(hits);

        baseMapper.updateById(houseHits);
    }

    private void insertHouseHits(Integer roomId) {
        HouseHits houseHits = HouseHits.builder()
                .roomId(roomId)
                .hits(1)
                .build();

        baseMapper.insert(houseHits);
    }

    private HouseHits selectHouseHits(Integer roomId) {
        QueryWrapper<HouseHits> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseHits::getRoomId, roomId)
                .eq(HouseHits::getDeleted, 0);
        return baseMapper.selectOne(queryWrapper);
    }
}
